#!/bin/sh /etc/rc.common
START=50

run_reboot()
{
	mkdir -p /var/lock
	lock /var/lock/autoreboot.lock
	local enable
	local minute
	local hour
	local grep_result
	config_get_bool enable $1 enable

	if [ $enable = 1 ]; then
		config_get week $1 week
		config_get minute $1 minute
		config_get hour $1 hour
		minute=$(printf "%d\n" $minute)
		hour=$(printf "%d\n" $hour)
		if [ $week = 7 ]; then week="*"; fi
		if [ $week = "*" ]; then
			grep_result=$(grep "^$minute $hour \* \* \* sleep 5 && touch /etc/banner && reboot$" /etc/crontabs/root)
		else
			grep_result=$(grep "^$minute $hour \* \* $week sleep 5 && touch /etc/banner && reboot$" /etc/crontabs/root)
		fi

		if [ -z "$grep_result" ]; then
			sed -i "/sleep 5 && touch \/etc\/banner && reboot$/d" /etc/crontabs/root >/dev/null 2>&1
			echo "$minute $hour * * $week sleep 5 && touch /etc/banner && reboot" >> /etc/crontabs/root
			/etc/init.d/cron reload
		fi
	else
		grep_result=$(grep "sleep 5 && touch /etc/banner && reboot$" /etc/crontabs/root)
		if [ -n "$grep_result" ]; then
			sed -i "/sleep 5 && touch \/etc\/banner && reboot$/d" /etc/crontabs/root >/dev/null 2>&1
			/etc/init.d/cron reload
		fi
	fi
	echo "Auto REBOOT has started."
	lock -u /var/lock/autoreboot.lock
}

start()
{
	config_load autoreboot
	config_foreach run_reboot login
}

stop()
{
	echo "Auto REBOOT has stoped."
}
